package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.dto.PermissionsDto;
import com.itheima.entity.Permissions;
import com.itheima.mapper.PermissionsMapper;
import com.itheima.service.PermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TangCheng
 * @date 2022/9/24 19:16
 * @description
 */
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements PermissionsService {

    @Autowired
    private PermissionsMapper permissionsMapper;

    @Override
    public List<Permissions> getPermissions(Long employeeId) {

        if (employeeId == null) {
            employeeId = BaseContext.getCurrent();
        }

        LambdaQueryWrapper<Permissions> wrapper = Wrappers.<Permissions>lambdaQuery()
                .eq(Permissions::getEmployeeId, employeeId)
                .orderByAsc(Permissions::getId);

        List<Permissions> permissions = permissionsMapper.selectList(wrapper);

        return permissions;
    }

    @Override
    public void setPermission(PermissionsDto permissionsDto) {

        // 先删除旧的权限，再添加新的权限
        this.remove(Wrappers.<Permissions>lambdaQuery().eq(Permissions::getEmployeeId, permissionsDto.getEmpId()));

        List<Permissions> results = new ArrayList<>();

        for (String permission : permissionsDto.getPermissions()) {

            String[] splits = permission.split(" ");

            if (splits.length != 2) {
                continue;
            }

            Permissions customPermission = new Permissions();
            customPermission.setMethodType(splits[0]);
            customPermission.setEmployeeId(permissionsDto.getEmpId());
            customPermission.setUrl(splits[1]);

            results.add(customPermission);
        }

        this.saveBatch(results);

    }
}
